<template>
  <view class="flex-col page">
	  <view class="navbar">
	  	<view class="back" @click="back">
	  		<u-icon name="arrow-left" size="45"></u-icon>
			
	  	</view>
	  	<text class="order">{{title == '' ? '客服咨询' : title }} </text>
	  </view>
	  <scroll-view scroll-y="true"  :style="{height:scrollHeight+'px',marginBottom:'40rpx',marginTop:'140rpx'}"  	:scroll-into-view="scrollView"
		
		:scroll-top="scrollTop"
		:refresher-triggered="triggered">
	  <view class="flex-col group" id="message-scroll">
		
	   <view class="flex-col group" v-for="item in messageList" :key="item.ID" >
	   	 <shop-tim-text-message  v-if="item.type === 'TIMTextElem'" :message="item" :isMine="item.flow === 'out'"></shop-tim-text-message>
	     <shop-tim-image-message  v-if="item.type === 'TIMImageElem'" :message="item" :isMine="item.flow === 'out'"></shop-tim-image-message>
		 <shop-tim-custom-message  v-if="item.type === 'TIMCustomElem'" :message="item" :isMine="item.flow === 'out'"></shop-tim-custom-message>
	   </view>
	</view>
	
	  
	  </scroll-view>
   <view class="flex-col group_9">
	   
      <view class="flex-col section_1">
		 
		    <view class="flex-row ">
        <view class="flex-col items-start search"> 
		<textarea
		style="width:100%;padding:10rpx 34rpx 10rpx 10rpx; border-radius: 50rpx;line-height: 50rpx;box-sizing: border-box;"
		  
			:adjust-position="true"
			cursor-spacing="40"
			v-model="value"
			placeholder="请输入...."
			maxlength="140"
			type="text"
			placeholderStyle="padding-left:20rpx;color:#B9B9B9;display:flex;align-items:center;"
		    :auto-height="true"
			@input="input"
			
		></textarea>
		 <!-- <u-textarea placeholderStyle="padding-left:10rpx;color:#B9B9B9" confirmType="done" @input="input" placeholder="请输入...." style="width: 100%;border-radius: 50rpx;" height="40" v-model="value" autoHeight :adjustPosition="true" :fixed="true" ref="textarea"></u-textarea> -->
		 </view>
      <view class="u-flex-col justify-center">
      	<image v-if="!value" @click="plus"
      	  src="https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/617a2ca7e4f1450011362b37/62b14c62d02982001153329a/16557868224858076433.png"
      	  class="image_5"
      	/>
      	<view class="send" v-if="value" @click="sendTextMessage">
      		<text>发送</text>
      	</view>
      </view>
	</view>
      </view>
      <view class="flex-col section_2" v-if="show && !value">
        <view class="flex-row group_10">
          <image   @tap="handleSendImage"
            src="https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/617a2ca7e4f1450011362b37/62b14c62d02982001153329a/16557868210427859343.png"
            class="image_6"
          />
          <image  @tap="handleSendPicture"
            src="https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/617a2ca7e4f1450011362b37/62b14c62d02982001153329a/16557868224805456153.png"
            class="image_6 image_8"
          />
		
		  <image  @click="handleSendOrder"
		    :src="imgUrl+'order2222.png'"
		    class="image_6 image_8"
		  />
        </view>
        <view class="flex-row group_11" >
          <text class="text_11" >图片</text>
          <text class="text_12">拍摄</text>
		   <text class="text_12">发送订单</text>
        </view>
      </view>
    </view>
	<shop-order-list class="tui-cards" :display="displayOrderList"  :orderMatch="orderMatch" @sendCustomMessage="$handleSendCustomMessage" @close="$handleCloseCards"></shop-order-list>
  </view>
</template>

<script>
  export default {
    components: {},
    data() {
      return {
		  	imgUrl:this.$IMG_URL,
		  orderMatch:[],
		  displayOrderList:false,
		  title:'',
		  scrollView: '',
		  kefu:'',
		  triggered: true,
		  scrollTop:100000000,
		  avatar: '',
		  userID: '',
		  show:false,
		  scrollHeight:0,
		  value:'',
		  conversationID:'',
		  conversationName:'',
		  conversation:[],
		  isShow:false,
		  avatar: '',
		  userID: '',
		  kefu:{},
		  customer:1,
		  // 当前会话
		  messageList: [],
		  // 自己的 ID 用于区分历史消息中，哪部分是自己发出的
		  scrollView: '',
		
		  triggered: true,
		  nextReqMessageID: '',
		  // 下一条消息标志
		  isCompleted: false // 当前会话消息是否已经请求完毕
	  };
    },
	/**
	 * 生命周期函数--监听页面加载
	 */
	async onLoad(options) {
		
		
	// 	// conversationID: C2C、 GROUP
        this.getOrder();
		console.log(` TUI-chat | onLoad | conversationID: ${options.conversationID}`);
		if(options.conversationID)
		{
			const { conversationID } = options;
			this.conversationID=conversationID;
		}else{
			let customer=-1;
			if(options.customer==0)
			{
				customer=options.customer;
				this.customer=options.customer;
			}
			
			let kefu=await this.getKefu(customer);
			this.kefu=kefu;
			console.log(kefu);
			if(kefu)
			{
			 const conversationID='C2C'+kefu.imUserId;
			 this.conversationID=conversationID;
			}
			
		}
		this.sendKefuMessage();
	   uni.$TUIKit
			.setMessageRead({
				conversationID:this.conversationID
			})
			.then(() => {
			 console.log('TUI-chat | setMessageRead  | ok');
			});
			console.log('id');
			console.log(this.conversationID);
		uni.$TUIKit.getConversationProfile(this.conversationID).then(res => {
	
			const { conversation } = res.data;
			
			this.conversation = conversation;
			this.setData({
				conversationName: this.getConversationName(conversation),
				isShow: conversation.type === 'GROUP'
			});
		
			if(this.kefu.hasOwnProperty('nickName'))
			{
			
					this.title=this.kefu.nickName
			
			}else{
				this.title=this.conversationName
			}
			console.log('title');
		   console.log(this.title);
			this.getMessageList(conversation)
		});
	},
	watch: {
		conversation: {
			handler: function(newVal) {
				if (!newVal.conversationID) return;
				this.setData(
					{
						conversation: newVal
					},
					() => {
						this.getMessageList(newVal);
					}
				);
			},
			immediate: true,
			deep: true
		}
	},
	destroyed() {
		// 一定要解除相关的事件绑定
		uni.$TUIKit.off(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived);
	},
	
	mounted() {
	this.getScrollHeight();
	uni.$TUIKit.getMyProfile().then(res => {
		this.avatar = res.data.avatar;
		this.userID = res.data.userID;
	});
	uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived, this);
	uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer, this);
	},
    methods: {
		handleSendOrder() {
			this.displayOrderList=true
		},
		getOrder()
		{
		this.$http('kefu.selectOrder').then(r=>{
			if(r.code==200)
			{
				if(r.data)
				{
				this.orderMatch=r.data;	
				}
				
			}
		});	
		},
		$handleSendCustomMessage(e)
		{
			const message = uni.$TUIKit.createCustomMessage({
				to: this.getToAccount(),
				conversationType: this.conversation.type,
				payload: e.detail.payload
			});
			this.$sendTIMMessage(message);
			this.displayOrderList=false;
		
			
		},
		$handleCloseCards()
		{
			this.displayOrderList=false
		},
		getKefu(customer)
		{
			let data={}
			if(customer==0)
			{
				data.customer=0
			}else{
				data.customer=1
			}
			return new Promise((resolve,reject)=>{
				this.$http('kefu.selectCustomer',data).then(r=>{
				  if(r.code==200)
				  {
					  resolve(r.data);
				  }else{
					  reject(false);
				  }
				})
			})
		
		},
		back() {
		   this.$http('kefu.pushMessageDuration',{customer:this.conversationID.replace('C2C', '')}).then(r=>{
			  if(r.code==200)
			  {
				  uni.navigateBack({
					  delta:1
				  })
			  }
		   });
		},
		sendKefuMessage()
		{
		   	this.$http('kefu.pushMessage',{
				fromUserId:this.userID,
				toUserId:this.conversationID.replace('C2C', '')
			}).then(r=>{
				console.log(r);
			})
		},
		getScrollHeight()
		{
			const query = uni.createSelectorQuery().in(this);
			query.select('.page').boundingClientRect();
			query.select('.group_9').boundingClientRect();
			query.exec(r=>{
				
					//进入页面滚动到底部
				 this.scrollHeight=r[0].height-r[1].height;
			
			});
			console.log(this.scrollHeight);
		},
		
		refresh() {
			if (this.isCompleted) {
				this.setData({
					isCompleted: true,
					triggered: false
				});
				return;
			}
			this.getMessageList(this.conversation);
			setTimeout(() => {
				this.setData({
					triggered: false
				});
			}, 2000);
		},
		checkSend()
		{
			console.log(this.kefu);
			// return true;
			return new Promise((resolve,reject)=>{
				this.$http('kefu.compare',{customer:this.conversationID.replace('C2C', '')}).then(r=>{
							 if(r.code==200)
							 {
								 if(r.data==true)
								 {
									resolve(true);
								 }else{
									 this.$u.toast('咨询时间已用完，请购买服务');
									 this.value='';
									reject(false);
								 }
							 }else{
								this.$u.toast('网络异常');
								reject(false);
							 }
			})
		 
		  });	
		},
		async handleSendPicture() {
			if(await this.checkSend())
			{
			   this.sendImageMessage('camera');
			}
		},
		async handleSendImage() {
			if(await this.checkSend())
			{
			this.sendImageMessage('album');
			}
		},
		
		async sendImageMessage(type) {
			if(await this.checkSend())
			{
			uni.chooseImage({
				sourceType: [type],
				count: 1,
				success: res => {
					if (res) {
						const message = uni.$TUIKit.createImageMessage({
							to: this.getToAccount(),
							conversationType: this.conversation.type,
							payload: {
								file: res
							},
							onProgress: percent => {
								message.percent = percent;
							}
						});
						this.$sendTIMMessage(message);
					}
				}
			});	
			}
			
		},
		// 消息已读更新
		$onMessageReadByPeer() {
			console.log('peer');
			this.setData({
				messageList: this.messageList
			});
		},
		// 收到的消息
		$onMessageReceived(value) {
			// 若需修改消息，需将内存的消息复制一份，不能直接更改消息，防止修复内存消息，导致其他消息监听处发生消息错误
			const event = value;
			const list = [];
			event.data.forEach(item => {
				if (item.conversationID === this.conversation.conversationID) {
					list.push(Object.assign(item));
				}
			});
			console.log(list);
			this.messageList = this.messageList.concat(list);
			// this.$onMessageReadByPeer();
			this.scrollToButtom();
		},
		
	scrollToButtom() {
		console.log('bottom');
		const query = uni.createSelectorQuery().in(this);
		
		let nodesRef = query.select('#message-scroll');
		nodesRef.boundingClientRect(res => {
			console.log(res.height);
				this.$nextTick(() => {
					//进入页面滚动到底部
					this.scrollTop = res.height+400;
				});
			})
			.exec();
	},
		getConversationName(conversation) {
			if (conversation.type === '@TIM#SYSTEM') {
				this.setData({
					showChat: false
				});
				return '系统通知';
			}
		
			if (conversation.type === 'C2C') {
				return conversation.remark || conversation.userProfile.nick || conversation.userProfile.userID;
			}
		
			if (conversation.type === 'GROUP') {
				return conversation.groupProfile.name || conversation.groupProfile.groupID;
			}
		},
	getMessageList(conversation) {
		if (!this.isCompleted) {
			uni.$TUIKit
				.getMessageList({
					conversationID: conversation.conversationID,
					nextReqMessageID: this.nextReqMessageID,
					count: 15
				})
				.then(res => {
					const { messageList } = res.data; // 消息列表。
					this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
					this.isCompleted = res.data.isCompleted; // 表示是否已经拉完所有消息。
					this.messageList = [...messageList, ...this.messageList];
					this.$handleMessageRender(this.messageList, messageList);
					console.log(this.messageList);
				});
		}
	},
	// 自己的消息上屏
	updateMessageList(msg) {
	
		this.messageList = [...this.messageList, msg];
		this.scrollToButtom();
	},
	// 历史消息渲染
		$handleMessageRender(messageList) {
			if (messageList.length > 0) {
				this.setData(
					{
						messageList
					},
					() => {}
				);
				this.$nextTick(() => {
					//进入页面滚动到底部
					this.scrollTop = 99999;
				});
			}
		},
		getToAccount() {
			if (!this.conversation || !this.conversation.conversationID) {
				return '';
			}
		
			switch (this.conversation.type) {
				case 'C2C':
					return this.conversation.conversationID.replace('C2C', '');
		
				case 'GROUP':
					return this.conversation.conversationID.replace('GROUP', '');
		
				default:
					return this.conversation.conversationID;
			}
		},
		async sendTextMessage() {
			let ok=await this.checkSend();
			console.log(ok);
			
			if(ok)
			{
			const to = this.getToAccount();
	
			if(this.value)
			{
				const message = uni.$TUIKit.createTextMessage({
					to,
					conversationType: this.conversation.type,
					payload: {
						text:this.value
					}
				});
				console.log('sendtextmessage');
				console.log(message);
				this.$sendTIMMessage(message);
				this.value='';
			}
		}else{
			this.value='';
		}
		},
		$sendTIMMessage(message) {
			const SDKAppID = getApp().globalData.SDKAppID;
		    uni.$TUIKit.sendMessage(message).then((res) => {
			    uni.$aegis.reportEvent({
					    name: 'sendMessage',
					    ext1: 'sendMessage-success',
					    ext2: 'uniTuikitExternal',
					    ext3: `${SDKAppID}`,
					})
					this.updateMessageList(message);
			}).catch((error) => {
				uni.$aegis.reportEvent({
						name: 'sendMessage',
						ext1: `sendMessage-failed#error: ${error}`,
						ext2: 'uniTuikitExternal',
						ext3: `${SDKAppID}`,
			  })
			})
				this.show=false;
		},
		plus()
		{
			this.show=!this.show;
			this.$nextTick(() => {
			this.getScrollHeight();
			this.scrollToButtom();
			});
			
		},
		input()
		{
		 this.show=false;	
		}
	},
  };
</script>

<style scoped lang="scss">
  .image_1 {
    border-radius: 50%;
    width: 80rpx;
    height: 80rpx;
  }
.back {
		position: absolute;
		left: 14rpx;
	}
::v-deep  .uni-textarea-textarea {
	 padding-left:20rpx
 }
	.navbar {
		padding-top: 100rpx;
		padding-bottom: 60rpx; ;
		height: 44px;
		background-color: #ffffff;
		width: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		top:0;
		left:0;
		right:0;
		
		
	}
  .image_6 {
    width: 116rpx;
    height: 116rpx;
  }
  .send{
	  width: 100rpx;
	  height: 60rpx;
	  background-color: #34BC52;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  font-size: 24rpx;
	  color: #f6f7f9;
	 
	  margin-left: 10rpx;
	  border-radius: 10rpx;
  }
  page{
	  background-color: #f2f2f2ff; 
  }
  .page {
    background-color: #f2f2f2ff;
    width: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	padding-bottom: 200rpx;
  }
  .group {
    padding-top: 43rpx;
    flex: 1 1 auto;
    overflow-y: auto;
  }

  .group_9 {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  }
  .text_1 {
    color: #666666;
    font-size: 24rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 28rpx;
  }
  .text_2 {
    margin-left: 10.5rpx;
    color: #666666;
    font-size: 24rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 28rpx;
  }
  .group_3 {
    width: 461rpx;
  }
  .image_2 {
    margin-left: 23rpx;
  }
  .text_5 {
    align-self: center;
    color: #666666;
    font-size: 24rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 28rpx;
  }
  .group_5 {
    margin-top: 40rpx;
  }
  .group_7 {
    margin-top: 40rpx;
  }
  .section_1 {
	width: 100vw;
padding:14rpx 32rpx;
   background: #F6F7F9;
   box-shadow: 0px -1px 0px 1px rgba(0,0,0,0.06);
   justify-content: center;
    // box-shadow: 0px -1rpx 0px 0px #0000000f;
    // border-bottom: solid 1rpx #eeeeee;
    position: relative;
  }
  .section_2 {
    padding: 40rpx 0 64rpx;
    background-color: #f6f7f9;
  }
  .text-wrapper {
    padding: 20rpx 0 26rpx;
    background-color: #1d6aff;
    border-radius: 16rpx;
  }
  .text_4 {
    margin-top: 10rpx;
    align-self: flex-end;
    color: #999999;
    font-size: 24rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 28rpx;
  }
  .group_6 {
    margin-left: 24rpx;
  }
  .text_9 {
    margin-right: 103rpx;
    margin-top: 5rpx;
    align-self: flex-end;
    color: #ff371d;
    font-size: 24rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 28rpx;
  }
  .search {
   flex:1;
   background: #FFFFFF;
   border-radius: 36rpx ;
   opacity: 1;
  
  }
  .image_5 {
    margin-left: 24rpx;
    flex-shrink: 0;
    align-self: center;
    width: 48rpx;
    height: 48rpx;
  }
  .group_10 {
    padding: 0 48rpx;
  }
  .group_11 {
    margin-top: 13rpx;
    padding: 0 83rpx;
  }
  .text_3 {
    margin-left: 16rpx;
    margin-right: 26rpx;
    color: #ffffff;
    font-size: 28rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 33rpx;
    text-align: left;
  }
  .text_6 {
    align-self: flex-start;
    color: #666666;
    font-size: 20rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 23rpx;
  }
  .text-wrapper_1 {
    margin-top: 17rpx;
    padding: 18rpx 0 29rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
  }
  .text-wrapper_2 {
    margin-right: 24rpx;
    padding: 24rpx 0 23rpx;
    background-color: #1d6aff;
    border-radius: 16rpx;
    height: 80rpx;
  }
  .text_10 {
    margin-left: 32rpx;
 
    font-size: 28rpx;
    font-family: '.AppleSystemUIFont';
  
  }
  .image_8 {
    margin-left: 72rpx;
  }
  .text_11 {
    color: #666666;
    font-size: 24rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 28rpx;
  }
  .text_12 {
    margin-left: 132rpx;
    color: #666666;
    font-size: 24rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 28rpx;
  }
  .text_7 {
    margin-left: 16rpx;
    margin-right: 15rpx;
    color: #333333;
    font-size: 28rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 33rpx;
  }
  .text_8 {
    margin-left: 16rpx;
    margin-right: 8rpx;
    color: #ffffff;
    font-size: 28rpx;
    font-family: '.AppleSystemUIFont';
    line-height: 33rpx;
  }
</style>